package com.zfl.thread.day03;

/**
 * 此版本先判断执行，再等待，会出现死锁
 * 最后会出现其他线程都结束了，最后一个线程依旧在等待，没有线程取唤醒
 * 当然可以判断是否是最后一次循环，如果是最后一次循环，则不wait()，较麻烦
 */


public class Demo02 {

    public static volatile boolean flag = true;
    public static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 1; i <= 1; i += 2) {
                synchronized (lock) {
                    if (flag) {
                        System.out.println("打印数字");
                        System.out.print(i);
                        System.out.println(i + 1);
                        flag = !flag;
                        lock.notify();
                        System.out.println("唤醒字母线程");
                    }
                    try {
                        System.out.println("数字线程等待");
                        lock.wait();//释放锁
                        System.out.println("数字线程被唤醒");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            System.out.println("数字线程结束");
        }, "数字").start();
        new Thread(() -> {
            for (int i = 0; i < 1; i++) {
                synchronized (lock) {
                    if (!flag) {
                        System.out.println("打印字母");
                        System.out.println((char) ('A' + i));
                        flag = !flag;
                        lock.notify();
                        System.out.println("唤醒数字你线程");
                    }
                    try {
                        System.out.println("字母线程等待");
                        lock.wait();//释放锁
                        System.out.println("字母线程被唤醒");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            System.out.println("字母线程结束");
        }, "字母").start();
    }
}
